package org.xbdframework.sample.sso.authserver.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.xbdframework.sample.sso.authserver.mapper.UserInfoMapper;
import org.xbdframework.sample.sso.authserver.model.Menu;
import org.xbdframework.sample.sso.authserver.model.Role;
import org.xbdframework.sample.sso.authserver.model.Users;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {

    @Resource
    private UserInfoMapper userInfoMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询数据库
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        Users users = userInfoMapper.selectOne(wrapper);
        if (users == null){
            throw new UsernameNotFoundException("用户不存在!");
        }

        //获得用户角色,菜单列表
        List<Role> roles = userInfoMapper.selectRoleByUserId(users.getId());
        List<Menu> menus = userInfoMapper.selectMenuByUserId(users.getId());

        //声明一个权限集合List<GrantedAuthority>
        List<GrantedAuthority> authorityList = new ArrayList<>();
        //加入角色
        for (Role role : roles) {
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority("ROLE_" + role.getName());
            authorityList.add(simpleGrantedAuthority);
        }
        //加入权限
        for (Menu menu : menus) {
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(menu.getPermission());
            authorityList.add(simpleGrantedAuthority);
        }
        /*
        * 参数一  用户名
        * 参数二 加密后的密码
        * 参数三 权限集合
        * */
      return new User(users.getUsername(),new BCryptPasswordEncoder().encode(users.getPassword()),authorityList);
    }
}
